package mju.cxf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import mju.cxf.dto.ProductCategoriesDTO;
import mju.cxf.entity.Categories;
import mju.cxf.entity.Product;
import mju.cxf.entity.ProductCategories;
import mju.cxf.mapper.CategoriesMapper;
import mju.cxf.mapper.ProductCategoriesMapper;
import mju.cxf.mapper.ProductMapper;
import mju.cxf.service.ProductCategoriesService;
import mju.cxf.utils.TimestampUpdaterUtils;
import mju.cxf.vo.ProductCategoryVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类和商品关联服务类
 * @author lechangxin,wangx,zhengx
 * @version 1.0
 * @see ProductCategoriesService
 */
@Service
public class ProductCategoriesServiceImpl extends ServiceImpl<ProductCategoriesMapper, ProductCategories> implements ProductCategoriesService {

    @Autowired
    private CategoriesMapper categoriesMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductCategoriesMapper productCategoriesMapper;

    /**
     * A新增商品分类信息
     *
     * @return boolean
     */
    @Override
    public boolean saveProductCategories(ProductCategoriesDTO productCategoriesDTO) {
        ProductCategories productCategories = new ProductCategories();
        BeanUtils.copyProperties(productCategoriesDTO, productCategories);
        TimestampUpdaterUtils.saveUtil(productCategories);
        return this.save(productCategories); // 使用 MyBatis-Plus 提供的 save() 方法
    }

    /**
     * A删除商品分类信息
     *
     * @return boolean
     */
    @Override
    public boolean deleteProductCategories(Integer productId) {
        return productCategoriesMapper.removeByPorductId(productId);
    }

    /**
     * A修改商品分类信息
     *
     * @return boolean
     */
    @Override
    public boolean updateProductCategories(Integer productId, Integer categoriesId) {
        return productCategoriesMapper.updateByProductId(productId, categoriesId);
    }

    /**
     * A新增多个商品分类信息
     *
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class,timeout = 5)
    public boolean saveProductCategoriess(List<ProductCategoriesDTO> productCategoriesDTOList) {
        // 从数据库中获取已存在的 productId 和 categoryId 组合
        List<ProductCategories> existingProductCategories = this.list();
        Set<String> existingProductCategoryIds = existingProductCategories.stream()
                .map(productCategories -> productCategories.getProductId() + "-" + productCategories.getCategoriesId())
                .collect(Collectors.toSet());

        List<ProductCategories> productCategoriesList = productCategoriesDTOList.stream()
                .filter(dto -> !existingProductCategoryIds.contains(dto.getProductId() + "-" + dto.getCategoriesId()))
                .map(dto -> {
                    ProductCategories productCategories = new ProductCategories();
                    BeanUtils.copyProperties(dto, productCategories);
                    TimestampUpdaterUtils.saveUtil(productCategories); // 确保这个方法能够处理批量操作
                    return productCategories;
                })
                .collect(Collectors.toList());

        // 如果 productCategoriesList 为空，则不执行操作，直接返回 true
        if (productCategoriesList.isEmpty()) {
            return true;
        }

        // 使用 MyBatis-Plus 提供的 saveBatch() 方法批量保存
        return this.saveBatch(productCategoriesList);
    }


    /**
     * A获取所有商品分类信息
     *
     * @return List
     */
    @Override
    public List<ProductCategories> getAllProductCategories() {
        return this.list();
    }

    /**
     * A批量删除商品分类信息
     *
     * @param productCategoriesDTO 商品分类列表
     * @return boolean
     **/
    @Override
    public boolean deleteProductCategoriess(List<ProductCategoriesDTO> productCategoriesDTO) {
        // 如果所有记录都存在，则执行删除操作
        return productCategoriesMapper.removeByProductIdAndCategories(productCategoriesDTO);
    }


    /**
     * U获取全部分类和商品
     *
     * @return categoriesAndProductVO 分类及商品信息
     */
    @Override
    public HashMap<String, Object> getAllCategoriesAndProduct() {
        LambdaQueryWrapper<Categories> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Categories::getState, 0);
        List<Categories> categories = categoriesMapper.selectList(lqw);
        List<ProductCategoryVO> productCategoryVOS = new ArrayList<>();
        for (Categories category : categories) {
            List<Product> products = productMapper.selectByCategoriesId(category.getId());
            ProductCategoryVO productCategoryVO = ProductCategoryVO.builder()
                    .imageUrl(category.getImageUrl())
                    .name(category.getName())
                    .id(category.getId())
                    .subCategoryList(products)
                    .build();
            productCategoryVOS.add(productCategoryVO);
        }
        HashMap<String, Object> resultStructure = new HashMap<>();
        resultStructure.put("categoryList", productCategoryVOS);
        resultStructure.put("currentCategory", productCategoryVOS.get(0));
        return resultStructure;
    }

    /**
     * U单个分类商品列表
     *
     * @param id 分类唯一标识符
     * @return ProductCategoryVO
     */
    @Override
    public ProductCategoryVO getCategoriesAndProductById(int id) {
        Categories category = categoriesMapper.selectById(id);
        List<Product> products = productMapper.selectByCategoriesId(id);
        return ProductCategoryVO.builder()
                .imageUrl(category.getImageUrl())
                .name(category.getName())
                .id(category.getId())
                .subCategoryList(products)
                .build();
    }

    /**
     * U进入一个商品规格列表页 获得商品
     *
     * @param productId 商品id
     * @param categoriesId 分类id
     * @return hashmap 商品兄弟 商品分类 和当前商品
     */
    @Override
    public HashMap<String, Object> getProductsByCategoriesId(int productId, int categoriesId) {
        categoriesId = categoriesId == 0 ? 1 : categoriesId;
        Categories category = categoriesMapper.selectById(categoriesId);
        List<Product> products = productMapper.selectByCategoriesId(categoriesId);
        Product product;
        if (productId != 0) {
            product = productMapper.selectById(productId);
        } else {
            product = products.get(0);
        }
        HashMap<String, Object> resultStructure = new HashMap<>();
        resultStructure.put("brotherCategory", products);
        resultStructure.put("parentCategory", category);
        resultStructure.put("currentCategory", product);
        return resultStructure;
    }

}
